<template>
  <div class="messages-page">
    <div class="messages-container">
      <div class="messages-sidebar">
        <div class="sidebar-header">
          <h2>消息</h2>
          <button class="new-message-btn">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M3 3L21 12L3 21V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        
        <div class="conversations-list">
          <!-- 加载状态 -->
          <div v-if="loading && conversations.length === 0" class="loading">
            加载中...
          </div>

          <!-- 会话列表 -->
          <div
            v-for="conversation in conversations"
            :key="conversation.id"
            class="conversation-item"
            :class="{ active: selectedConversation === conversation.id }"
            @click="selectConversation(conversation.id)"
          >
            <div class="user-avatar">
              <img
                :src="conversation.avatar"
                :alt="conversation.name"
                @error="handleAvatarError"
              />
              <div v-if="conversation.isOnline" class="online-indicator"></div>
            </div>
            <div class="conversation-info">
              <div class="conversation-header">
                <span class="user-name">{{ conversation.name }}</span>
                <span class="message-time">{{ conversation.lastMessageTime }}</span>
              </div>
              <div class="last-message">
                <span :class="{ unread: conversation.unreadCount > 0 }">
                  {{ conversation.lastMessage || '暂无消息' }}
                </span>
                <div v-if="conversation.unreadCount > 0" class="unread-badge">
                  {{ conversation.unreadCount }}
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && conversations.length === 0" class="empty-conversations">
            <p>暂无会话</p>
          </div>
        </div>
      </div>
      
      <div class="chat-area">
        <div v-if="selectedConversation" class="chat-container">
          <div class="chat-header">
            <div class="chat-user-info">
              <img :src="currentChat.avatar" :alt="currentChat.name" class="user-avatar" />
              <div>
                <div class="user-name">{{ currentChat.name }}</div>
                <div class="user-status">{{ currentChat.isOnline ? '在线' : '离线' }}</div>
              </div>
            </div>
            <div class="chat-actions">
              <button class="action-btn">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M22 16.92V19C22 19.5304 21.7893 20.0391 21.4142 20.4142C21.0391 20.7893 20.5304 21 20 21C15.0294 21 10.196 19.206 6.29799 15.908C3.02399 12.986 1.00799 8.814 1.00799 4.5C1.00799 3.96957 1.21871 3.46086 1.59378 3.08579C1.96885 2.71071 2.47756 2.5 3.00799 2.5H5.07799C5.32799 2.5 5.56799 2.61 5.72799 2.8C5.88799 2.99 5.95799 3.24 5.91799 3.49L5.51799 6.24C5.47799 6.49 5.35799 6.72 5.17799 6.89C4.99799 7.06 4.76799 7.15 4.51799 7.15H3.00799C3.00799 11.229 6.27899 14.5 10.358 14.5V12.99C10.358 12.74 10.448 12.51 10.618 12.33C10.788 12.15 11.018 12.03 11.268 11.99L14.018 11.59C14.268 11.55 14.518 11.62 14.708 11.78C14.898 11.94 15.008 12.18 15.008 12.43V14.5C15.008 15.0304 14.7973 15.5391 14.4222 15.9142C14.0471 16.2893 13.5384 16.5 13.008 16.5H11.008" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </button>
              <button class="action-btn">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <polygon points="23,7 16,12 23,17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <rect x="1" y="5" width="15" height="14" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                </svg>
              </button>
            </div>
          </div>
          
          <div class="messages-area">
            <!-- 消息加载状态 -->
            <div v-if="messageLoading && messages.length === 0" class="loading">
              加载消息中...
            </div>

            <!-- 消息列表 -->
            <div
              v-for="message in currentMessages"
              :key="message.id"
              class="message"
              :class="{ sent: message.isSent, received: !message.isSent }"
            >
              <div v-if="!message.isSent" class="message-avatar">
                <img
                  :src="message.senderAvatar || currentChat?.avatar || 'https://picsum.photos/40/40?random=default'"
                  :alt="currentChat?.name || '用户'"
                  @error="handleAvatarError"
                />
              </div>
              <div class="message-content">
                <div class="message-bubble">
                  <!-- 文本消息 -->
                  <span v-if="message.messageType === 1">{{ message.content }}</span>

                  <!-- 图片消息 -->
                  <img
                    v-else-if="message.messageType === 2 && message.mediaUrl"
                    :src="message.mediaUrl"
                    alt="图片消息"
                    class="message-image"
                    @error="handleImageError"
                  />

                  <!-- 视频消息 -->
                  <video
                    v-else-if="message.messageType === 3 && message.mediaUrl"
                    :src="message.mediaUrl"
                    controls
                    class="message-video"
                  />

                  <!-- 其他类型消息 -->
                  <span v-else>{{ message.content || '[不支持的消息类型]' }}</span>
                </div>
                <div class="message-time">
                  {{ message.time }}
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!messageLoading && messages.length === 0" class="empty-messages">
              <p>暂无消息，开始聊天吧！</p>
            </div>
          </div>
          
          <div class="message-input-area">
            <div class="input-container">
              <button class="emoji-btn">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                  <path d="M8 14S9.5 16 12 16S16 14 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <line x1="9" y1="9" x2="9.01" y2="9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <line x1="15" y1="9" x2="15.01" y2="9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </button>
              <input 
                type="text" 
                placeholder="发送消息..." 
                v-model="newMessage"
                @keyup.enter="sendMessage"
              />
              <button class="send-btn" @click="sendMessage" :disabled="!newMessage.trim()">
                发送
              </button>
            </div>
          </div>
        </div>
        
        <div v-else class="no-chat-selected">
          <div class="no-chat-content">
            <svg width="96" height="96" viewBox="0 0 24 24" fill="none">
              <path d="M21 15C21 15.5304 20.7893 16.0391 20.4142 16.4142C20.0391 16.7893 19.5304 17 19 17H7L3 21V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H19C19.5304 3 20.0391 3.21071 20.4142 3.58579C20.7893 3.96086 21 4.46957 21 5V15Z" stroke="#8e8e8e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <h3>你的消息</h3>
            <p>向朋友发送私人照片和消息</p>
            <button class="send-message-btn">发送消息</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {
  getConversationList,
  getMessageList,
  markConversationAsRead,
  sendMessage as sendMessageApi
} from '@/api/message';
import {getMediaUrl} from '@/utils/media';
import {useChat} from '@/composables/useChat';

const route = useRoute();
const router = useRouter();
const selectedConversation = ref(null);
const newMessage = ref('');
const loading = ref(false);
const messageLoading = ref(false);

// WebSocket连接
const { isConnected, sendMessage: sendWsMessage, onMessage } = useChat();

// 会话列表数据
const conversations = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const totalUnreadCount = ref(0);

// 消息列表数据
const messages = ref([]);
const messageCurrentPage = ref(1);
const messagePageSize = ref(50);
const messageTotal = ref(0);
const currentUserId = ref('');

// 计算属性
const currentChat = computed(() => {
  return conversations.value.find(c => c.id === selectedConversation.value);
});

const currentMessages = computed(() => {
  return messages.value || [];
});

// 加载会话列表
const loadConversations = async () => {
  try {
    loading.value = true;
    const response = await getConversationList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });

    if (response.code === 200) {
      const data = response.data;
      conversations.value = data.conversations.map(item => ({
        id: item.id,
        name: item.otherNickname || item.otherUsername,
        username: item.otherUsername,
        avatar: item.otherAvatar ? getMediaUrl(item.otherAvatar) : 'https://picsum.photos/40/40?random=default',
        lastMessage: formatLastMessage(item.lastMessageContent, item.lastMessageType),
        lastMessageTime: formatTime(item.lastMessageTime),
        unreadCount: item.unreadCount || 0,
        isOnline: item.otherIsOnline || false,
        otherUserId: item.otherUserId
      }));

      total.value = data.total;
      totalUnreadCount.value = data.totalUnreadCount || 0;
    }
  } catch (error) {
    console.error('加载会话列表失败:', error);
    ElMessage.error('加载会话列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载消息列表
const loadMessages = async (conversationId) => {
  if (!conversationId) return;

  try {
    messageLoading.value = true;
    const response = await getMessageList({
      conversationId,
      pageNum: messageCurrentPage.value,
      pageSize: messagePageSize.value,
      sortType: 1 // 时间正序
    });

    if (response.code === 200) {
      const data = response.data;
      messages.value = data.messages.map(item => ({
        id: item.id,
        content: item.content,
        mediaUrl: item.mediaUrl ? getMediaUrl(item.mediaUrl) : null,
        messageType: item.messageType,
        isSent: item.senderId === currentUserId.value,
        time: formatTime(item.createdTime),
        senderId: item.senderId,
        senderAvatar: item.senderAvatar ? getMediaUrl(item.senderAvatar) : null,
        isRead: item.isRead === 1
      }));

      messageTotal.value = data.total;
    }
  } catch (error) {
    console.error('加载消息列表失败:', error);
    ElMessage.error('加载消息列表失败');
  } finally {
    messageLoading.value = false;
  }
};

// 选择会话
const selectConversation = async (id) => {
  selectedConversation.value = id;

  // 加载消息列表
  await loadMessages(id);

  // 标记会话为已读
  try {
    await markConversationAsRead(id);
    // 更新本地未读数
    const conversation = conversations.value.find(c => c.id === id);
    if (conversation) {
      totalUnreadCount.value -= conversation.unreadCount;
      conversation.unreadCount = 0;
    }
  } catch (error) {
    console.error('标记已读失败:', error);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || !selectedConversation.value) return;

  const currentChat = conversations.value.find(c => c.id === selectedConversation.value);
  if (!currentChat) return;

  try {
    const messageData = {
      receiverId: currentChat.otherUserId,
      messageType: 1, // 文本消息
      content: newMessage.value.trim()
    };

    const response = await sendMessageApi(messageData);

    if (response.code === 200) {
      // 添加到本地消息列表
      const newMsg = {
        id: response.data.id,
        content: newMessage.value.trim(),
        messageType: 1,
        isSent: true,
        time: formatTime(new Date()),
        senderId: currentUserId.value,
        isRead: 0
      };

      messages.value.push(newMsg);

      // 更新会话的最后消息
      currentChat.lastMessage = newMessage.value.trim();
      currentChat.lastMessageTime = formatTime(new Date());

      // 通过WebSocket发送消息通知（后端已经处理推送，这里不需要重复发送）
      console.log('消息发送成功，WebSocket连接状态:', isConnected.value);

      newMessage.value = '';
    } else {
      throw new Error(response.message || '发送失败');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error(error.message || '发送消息失败');
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';

  const time = new Date(timeStr);
  const now = new Date();
  const diff = now - time;

  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return time.toLocaleDateString();
};

// 格式化最后消息内容
const formatLastMessage = (content, messageType) => {
  if (!content) return '';

  switch (messageType) {
    case 1:
      return content;
    case 2:
      return '[图片]';
    case 3:
      return '[视频]';
    case 4:
      return '[语音]';
    case 5:
      return '[位置]';
    default:
      return content;
  }
};

// 键盘事件处理
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};

// 获取当前用户ID
const getCurrentUserId = async () => {
  try {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const user = JSON.parse(userInfo);
      currentUserId.value = user.userId || user.id;
      return;
    }

    // 如果没有用户信息，可以调用API获取
    // 这里暂时使用默认值，实际项目中需要调用getCurrentUserInfo API
    console.warn('未找到用户信息，请确保已登录');
  } catch (error) {
    console.error('获取用户ID失败:', error);
  }
};

// WebSocket消息处理
const handleWebSocketMessage = (wsData) => {
  console.log('收到WebSocket消息:', wsData);

  if (wsData.type === 'private_message') {
    const messageData = wsData.data;
    console.log('处理私信消息:', messageData);

    // 如果是当前会话的消息，添加到消息列表
    if (messageData.conversationId === selectedConversation.value) {
      const newMsg = {
        id: messageData.messageId,
        content: messageData.content,
        messageType: messageData.messageType || 1,
        isSent: messageData.senderId === currentUserId.value,
        time: formatTime(messageData.createdTime || new Date()),
        senderId: messageData.senderId,
        senderAvatar: messageData.senderAvatar ? getMediaUrl(messageData.senderAvatar) : null,
        isRead: 0
      };

      messages.value.push(newMsg);
      console.log('消息已添加到当前会话');
    }

    // 更新会话列表中的最后消息
    const conversation = conversations.value.find(c => c.id === messageData.conversationId);
    if (conversation) {
      conversation.lastMessage = formatLastMessage(messageData.content, messageData.messageType || 1);
      conversation.lastMessageTime = formatTime(messageData.createdTime || new Date());

      // 如果不是当前会话，增加未读数
      if (messageData.conversationId !== selectedConversation.value) {
        conversation.unreadCount++;
        totalUnreadCount.value++;
      }
      console.log('会话列表已更新');
    } else {
      console.log('未找到对应的会话，重新加载会话列表');
      // 如果找不到会话，重新加载会话列表
      loadConversations();
    }

    // 显示消息通知
    if (messageData.senderId !== currentUserId.value) {
      ElMessage.info(`收到来自 ${messageData.senderUsername || '用户'} 的消息`);
    }
  }
};

// 初始化
onMounted(async () => {
  await getCurrentUserId();
  await loadConversations();

  // 如果URL中有会话ID参数，自动选择该会话
  if (route.query.conversationId) {
    selectedConversation.value = route.query.conversationId;
    await loadMessages(route.query.conversationId);
  }

  // 注册WebSocket消息处理
  onMessage('private_message', handleWebSocketMessage);

  // 检查WebSocket连接状态
  setTimeout(() => {
    console.log('WebSocket连接状态:', isConnected.value);
    if (!isConnected.value) {
      console.warn('WebSocket未连接，可能无法接收实时消息');
    }
  }, 2000);
});

// 监听路由变化
watch(() => route.query.conversationId, async (newConversationId) => {
  if (newConversationId && newConversationId !== selectedConversation.value) {
    selectedConversation.value = newConversationId;
    await loadMessages(newConversationId);
  }
});

// 错误处理函数
const handleAvatarError = (event) => {
  event.target.src = 'https://picsum.photos/40/40?random=avatar_error';
};

const handleImageError = (event) => {
  event.target.src = 'https://picsum.photos/200/200?random=image_error';
};
</script>

<style lang="scss" scoped>
.messages-page {
  width: 100%;
  height: 100vh;
  background-color: #ffffff;
  color: #000000;
}

.messages-container {
  display: flex;
  height: 100vh;
  margin: 0 auto;
}

.messages-sidebar {
  width: 350px;
  border-right: 1px solid #262626;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 20px;
  border-bottom: 1px solid #262626;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    margin: 0;
  }
  
  .new-message-btn {
    background: none;
    border: none;
    color: #000000;
    cursor: pointer;
    padding: 8px;
    border-radius: 8px;
    
    &:hover {
      background-color: #ceb9b9;
    }
  }
}

.conversations-list {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  
  &:hover {
    background-color: #dbd2d2;
  }
  
  &.active {
    background-color: #0095F6;
    color:#fff;
  }
  
  .user-avatar {
    position: relative;
    
    img {
      width: 56px;
      height: 56px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .online-indicator {
      position: absolute;
      bottom: 2px;
      right: 2px;
      width: 14px;
      height: 14px;
      background-color: #00d95f;
      border: 2px solid #000;
      border-radius: 50%;
    }
  }
  
  .conversation-info {
    flex: 1;
    min-width: 0;
  }
  
  .conversation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
    
    .user-name {
      font-size: 14px;
      font-weight: 600;
    }
    
    .message-time {
      font-size: 12px;
    }
  }
  
  .last-message {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      
      &.unread {
        font-weight: 600;
      }
    }
    
    .unread-badge {
      background-color: #0095f6;
      color: #fff;
      font-size: 12px;
      font-weight: 600;
      padding: 2px 6px;
      border-radius: 10px;
      min-width: 18px;
      text-align: center;
    }
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #262626;
  
  .chat-user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .user-name {
      font-size: 16px;
      font-weight: 600;
      color: #fff;
    }
    
    .user-status {
      font-size: 12px;
      color: #8e8e8e;
    }
  }
  
  .chat-actions {
    display: flex;
    gap: 12px;
    
    .action-btn {
      background: none;
      border: none;
      color: #fff;
      cursor: pointer;
      padding: 8px;
      border-radius: 8px;
      
      &:hover {
        background-color: #1a1a1a;
      }
    }
  }
}

.messages-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  gap: 8px;
  
  &.sent {
    justify-content: flex-end;
    
    .message-content {
      align-items: flex-end;
    }
    
    .message-bubble {
      background-color: #0095f6;
      color: #fff;
    }
  }
  
  &.received {
    justify-content: flex-start;
    
    .message-content {
      align-items: flex-start;
    }
    
    .message-bubble {
      background-color: #262626;
      color: #fff;
    }
  }
  
  .message-avatar {
    img {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      object-fit: cover;
    }
  }
  
  .message-content {
    display: flex;
    flex-direction: column;
    max-width: 70%;
  }
  
  .message-bubble {
    padding: 8px 12px;
    border-radius: 18px;
    font-size: 14px;
    line-height: 1.4;

    .message-image {
      max-width: 200px;
      max-height: 200px;
      border-radius: 8px;
      cursor: pointer;
      display: block;
    }

    .message-video {
      max-width: 250px;
      max-height: 200px;
      border-radius: 8px;
      display: block;
    }
  }
  
  .message-time {
    font-size: 11px;
    color: #8e8e8e;
    margin-top: 4px;
    padding: 0 4px;
  }
}

// 加载状态和空状态样式
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #8e8e8e;
  font-size: 14px;
}

.empty-conversations {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
  color: #8e8e8e;
  font-size: 14px;
}

.empty-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #8e8e8e;
  font-size: 14px;
}

.message-input-area {
  padding: 20px;
  border-top: 1px solid #262626;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: #d9d9d9;
  border-radius: 22px;
  padding: 8px 16px;
  
  .emoji-btn {
    background: none;
    border: none;
    color: #8e8e8e;
    cursor: pointer;
    padding: 4px;
  }
  
  input {
    flex: 1;
    background: none;
    border: none;
    color: #fff;
    font-size: 14px;
    outline: none;
    
    &::placeholder {
      color: #8e8e8e;
    }
  }
  
  .send-btn {
    background: none;
    border: none;
    color: #0095f6;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    
    &:disabled {
      color: #8e8e8e;
      cursor: not-allowed;
    }
  }
}

.no-chat-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-chat-content {
  text-align: center;
  
  h3 {
    font-size: 22px;
    font-weight: 300;
    margin: 16px 0 8px;
  }
  
  p {
    color: #8e8e8e;
    font-size: 14px;
    margin-bottom: 24px;
  }
  
  .send-message-btn {
    background-color: #0095f6;
    color: #fff;
    border: none;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    
    &:hover {
      background-color: #1877f2;
    }
  }
}
</style>